<?php

namespace app\admin\controller;

use app\admin\model\Admin;
use app\admin\model\User;
use app\common\controller\Backend;
use app\common\model\Attachment;
use fast\Date;
use think\Db;
use app\admin\model\store\Shop;
use app\admin\model\service\Service;
use app\admin\model\staff\Staff;
use app\admin\model\wanlshop\Order;
use think\Session;

/**
 * 运营概况
 *
 * @icon   fa fa-dashboard
 * @remark 用于展示当前系统中的统计数据、统计报表及重要实时数据
 */
class Management extends Backend
{

    /**
     * 查看
     */
    public function index()
    {
        try {
            \think\Db::execute("SET @@sql_mode='';");
        } catch (\Exception $e) {

        }
        $this->request->filter(['strip_tags']);
        $starttime = strtotime($this->request->request('starttime'));
        $endtime = strtotime($this->request->request('endtime'));

        $column = [];
        if (!$starttime) {
            $starttime = Date::unixtime('day', 0);
            $endtime = Date::unixtime('day', 0, 'end');
        }


        $joinlist = Db("user")->where('jointime', 'between time', [$starttime, $endtime])
            ->field('jointime, status, COUNT(*) AS nums, DATE_FORMAT(FROM_UNIXTIME(jointime), "%Y-%m-%d") AS join_date')
            ->group('join_date')
            ->select();
        for ($time = $starttime; $time <= $endtime; ) {
            $column[] = date("Y-m-d", $time);
            $time += 86400;
        }
        $userlist = array_fill_keys($column, 0);
        foreach ($joinlist as $k => $v) {
            $userlist[$v['join_date']] = $v['nums'];
        }

        $dbTableList = Db::query("SHOW TABLE STATUS");
        $addonList = get_addon_list();
        $totalworkingaddon = 0;
        $totaladdon = count($addonList);
        foreach ($addonList as $index => $item) {
            if ($item['state']) {
                $totalworkingaddon += 1;
            }
        }


        $shop_id = Session::get('shop');
        $where2 = [];
        $where3 = [];
        $where2['o.data_type'] = ['<>','merchant'];
        $where3['o.data_type'] = ['<>','merchant'];
        if ($shop_id != 1) {
            $where2['o.shop_id'] = $shop_id;
            $where3['o.shop_id'] = $shop_id;
        }

        $data1 = Db::name("wanlshop_order")->alias('o')
            ->where('o.createtime', 'between time', [$starttime, $endtime])
            //->where('o.shop_id','=',$shop_id)
            ->where($where2)
            ->where('o.state', 'in', '2,3,4,5,6')
            ->where('g.gdtype', '=', '0')
            ->join('wanlshop_order_goods g', 'g.order_id=o.id', 'left')
            ->where('g.id', '>', 0)
            ->field('DATE_FORMAT(FROM_UNIXTIME(o.createtime), "%Y-%m-%d") AS o_date,sum(g.actual_payment  * g.number) as o_sum,count(distinct o.id) as o_no')
            ->group('o_date')
            ->select();

        $data2 = Db::name("wanlshop_order")->alias('o')
            ->where('o.createtime', 'between time', [$starttime, $endtime])
            // ->where('o.shop_id','=',$shop_id)
            ->where($where2)
            ->where('o.state', 'in', '2,3,4,5,6')
            ->where('g.gdtype', '=', '1')
            ->join('wanlshop_order_goods g', 'g.order_id=o.id', 'left')
            ->where('g.id', '>', 0)
            ->field('DATE_FORMAT(FROM_UNIXTIME(o.createtime), "%Y-%m-%d") AS o_date,sum(g.actual_payment * g.number) as o_sum,count(distinct o.id) as o_no')
            ->group('o_date')
            ->select();

        $data3 = Db::name("wanlshop_order")->alias('o')
            ->where('o.createtime', 'between time', [$starttime, $endtime])
            //->where('o.shop_id','=',$shop_id)
            ->where($where2)
            ->where('o.state', 'in', '2,3,4,5,6')
            //->where('g.gdtype','=','1')
            ->join('wanlshop_order_item g', 'g.order_id=o.id', 'left')
            ->where('g.id', '>', 0)
            ->field('DATE_FORMAT(FROM_UNIXTIME(o.createtime), "%Y-%m-%d") AS o_date,sum(g.actual_price) as o_sum,count(distinct o.id) as o_no')
            ->group('o_date')
            ->select();

        $data4 = Db::name("wanlshop_order")->alias('o')
            ->where('o.createtime', 'between time', [$starttime, $endtime])
            // ->where('o.shop_id','=',$shop_id)
            ->where($where2)
            ->where('o.state', 'in', '2,3,4,5,6')
            //->where('g.gdtype','=','0')
            //->join('wanlshop_order_goods g','g.order_id=o.id','left')
            ->field('DATE_FORMAT(FROM_UNIXTIME(o.createtime), "%Y-%m-%d") AS o_date,count(distinct o.id) as o_no')
            ->group('o_date')
            ->select();

        $orderlist = array_fill_keys($column, 0);
        $order_slist = array_fill_keys($column, 0);
        foreach ($data1 as $k => $v) {
            $orderlist[$v['o_date']] = $v['o_no'];
            $order_slist[$v['o_date']] = $v['o_sum'];
        }
        $orderlist2 = array_fill_keys($column, 0);
        $order_slist2 = array_fill_keys($column, 0);
        foreach ($data2 as $k => $v) {
            $orderlist2[$v['o_date']] = $v['o_no'];
            $order_slist2[$v['o_date']] = $v['o_sum'];
        }
        $orderlist3 = array_fill_keys($column, 0);
        $order_slist3 = array_fill_keys($column, 0);
        foreach ($data3 as $k => $v) {
            $orderlist3[$v['o_date']] = $v['o_no'];
            $order_slist3[$v['o_date']] = $v['o_sum'];
        }
        $orderlist4 = array_fill_keys($column, 0);
        foreach ($data4 as $k => $v) {
            $orderlist4[$v['o_date']] = $v['o_no'];
            //$order_slist3[$v['o_date']] = $v['o_sum'];
        }
        $orderlist5 = array_fill_keys($column, 0);
        foreach ($data4 as $k => $v) {
            $orderlist5[$v['o_date']] = $userlist[$v['o_date']] + $v['o_no'];
            //$order_slist3[$v['o_date']] = $v['o_sum'];
        }

        //获取支付方式
        $list9 = [];
        $list9 = Db::name('pay')->where('status','normal')->field('id,name')->order('weigh desc')->select();
        if (count($list9) > 0) {
            $where3['o.createtime'] = ['between time',[$starttime, $endtime]];
            $where3['o.state'] = 6;
            $total_real_count = Db::name('wanlshop_order')->alias('o')
                    ->join('wanlshop_pay_out_trade t', 'o.id=t.order_id', 'left')
                    ->where($where3)
                    ->count();
            $total_real_amount = Db::name('wanlshop_order')->alias('o')
                    ->join('wanlshop_pay_out_trade t', 'o.id=t.order_id', 'left')
                    ->where($where3)
                    ->sum('actual_price');
            $total_pending_count = 0;
            $total_pending_amount = 0;
            $total_refund_count = 0;
            $total_refund_amount = 0;


            foreach ($list9 as $key => &$val) {
                $where3['o.state'] = 1;
                $where3['t.pay_way_id'] = $val['id'];
                //收款笔数
                $val['pending_count'] = Db::name('wanlshop_order')->alias('o')
                    ->join('wanlshop_pay_out_trade t', 'o.id=t.order_id', 'left')
                    ->where($where3)
                    ->count();
                $val['pending_amount'] = Db::name('wanlshop_order')->alias('o')
                    ->join('wanlshop_pay_out_trade t', 'o.id=t.order_id', 'left')
                    ->where($where3)
                    ->sum('actual_price');
                $total_pending_count += $val['pending_count'];
                $total_pending_amount += $val['pending_amount'];

                //退款笔数
                $where3['o.state'] = 11;
                $val['refund_count'] = Db::name('wanlshop_order')->alias('o')
                    ->join('wanlshop_pay_out_trade t', 'o.id=t.order_id', 'left')
                    ->where($where3)
                    ->count();
                $val['refund_amount'] = Db::name('wanlshop_order')->alias('o')
                    ->join('wanlshop_pay_out_trade t', 'o.id=t.order_id', 'left')
                    ->where($where3)
                    ->sum('actual_price');
                $total_refund_count += $val['refund_count'];
                $total_refund_amount += $val['refund_amount'];

                //实收笔数
                $where3['o.state'] = 6;
                $val['real_count'] = Db::name('wanlshop_order')->alias('o')
                    ->join('wanlshop_pay_out_trade t', 'o.id=t.order_id', 'left')
                    ->where($where3)
                    ->count();
                $val['real_amount'] = Db::name('wanlshop_order')->alias('o')
                    ->join('wanlshop_pay_out_trade t', 'o.id=t.order_id', 'left')
                    ->where($where3)
                    ->sum('actual_price');
                $val['count_proportion']  = '0%';
                $val['amount_proportion']  = '0%';
                if($total_real_count > 0){
                    $val['count_proportion'] = number_format($val['real_count'] / $total_real_count * 100, 1) . '%';
                }
                if($total_real_amount > 0){
                    $val['amount_proportion'] = number_format($val['real_amount'] / $total_real_amount * 100, 1) . '%';
                }
            }

            $total_info = [];
            $total_info['name'] = '合计';
            $total_info['pending_count'] = $total_pending_count;
            $total_info['pending_amount'] = $total_pending_amount;
            $total_info['refund_count'] = $total_refund_count;
            $total_info['refund_amount'] = $total_refund_amount;
            $total_info['real_count'] = $total_real_count;
            $total_info['real_amount'] = $total_real_amount;
            $total_info['count_proportion'] = '-';
            $total_info['amount_proportion'] = '-';
            $list9[] = $total_info;
        }

        $list22 = Db::name('wanlshop_order_goods')->alias('i')
            ->join('wanlshop_order o', 'o.id=i.order_id', 'left')
            ->join('wanlshop_pay_out_trade t', 'o.id=t.order_id', 'left')
            ->join('pay p', 'p.id=t.pay_way_id', 'left')
            ->where($where2)
            ->where('p.type','<>','1')
            ->where('o.createtime', 'between time', [$starttime, $endtime])
            ->field('sum(i.number * i.actual_payment ) as sum')
            ->where('o.state',  '6')
            ->where('i.gdtype',  '1')
            ->select();
        $list23 = Db::name('wanlshop_order_goods')->alias('i')
            ->join('wanlshop_order o', 'o.id=i.order_id', 'left')
            ->join('wanlshop_pay_out_trade t', 'o.id=t.order_id', 'left')
            ->join('pay p', 'p.id=t.pay_way_id', 'left')
            ->where($where2)
            ->where('p.type','<>','1')
            ->where('o.createtime', 'between time', [$starttime, $endtime])
            ->field('sum(i.number * i.actual_payment ) as sum')
            ->where('o.state', '6')
            ->where('i.gdtype', '0')
            ->select();



        $this->view->assign([
            'totaluser' => User::count(),
            'totaladdon' => $totaladdon,
            'totaladmin' => Admin::count(),
            'totalcategory' => \app\common\model\Category::count(),
            'todayusersignup' => User::whereTime('jointime', 'today')->count(),
            'todayuserlogin' => User::whereTime('logintime', 'today')->count(),
            'sevendau' => User::whereTime('jointime|logintime|prevtime', '-7 days')->count(),
            'thirtydau' => User::whereTime('jointime|logintime|prevtime', '-30 days')->count(),
            'threednu' => User::whereTime('jointime', '-3 days')->count(),
            'sevendnu' => User::whereTime('jointime', '-7 days')->count(),
            'dbtablenums' => count($dbTableList),
            'dbsize' => array_sum(array_map(function ($item) {
                return $item['Data_length'] + $item['Index_length'];
            }, $dbTableList)),
            'totalworkingaddon' => $totalworkingaddon,
            'attachmentnums' => Attachment::count(),
            'attachmentsize' => Attachment::sum('filesize'),
            'picturenums' => Attachment::where('mimetype', 'like', 'image/%')->count(),
            'picturesize' => Attachment::where('mimetype', 'like', 'image/%')->sum('filesize'),
            'starttime' => $starttime,
            'endtime' => $endtime,
            'pay' => Db::name('wanlshop_order')->alias('o')
                    ->join('wanlshop_pay_out_trade t', 'o.id=t.order_id', 'left')
                    ->join('pay p', 'p.id=t.pay_way_id', 'left')
                    ->where('o.createtime', 'between time', [$starttime, $endtime])
                    ->where($where2)
                    ->where('p.type','<>','1')
                    ->where('o.state', 6)
                    ->sum('o.actual_price'),

            'pay_1' => Db::name('wanlshop_order')->alias('o')
                ->where($where2)
                ->where('o.createtime', 'between time', [$starttime, $endtime])
                ->where('o.state', 11)
                ->sum('o.actual_price'),

            'pay_2' => Db::name('wanlshop_order_item')->alias('i')
                ->join('wanlshop_order o', 'o.id=i.order_id', 'left')
                ->join('wanlshop_pay_out_trade t', 'o.id=t.order_id', 'left')
                ->join('pay p', 'p.id=t.pay_way_id', 'left')
                ->where($where2)
                ->where('p.type','<>','1')
                ->where('o.createtime', 'between time', [$starttime, $endtime])
                ->where('o.state', 'in', '2,3,4,5,6')
                ->sum('i.actual_price'),
            // 'pay_3' => Db::name('wanlshop_order_goods')->alias('i')
            // ->join('wanlshop_order o','o.id=i.order_id','left')
            // ->where('o.createtime', 'between time', [$starttime, $endtime])
            // ->where('o.state','in','2,3,4,5,6')
            // ->where('i.gdtype','=','1')
            // ->sum('i.actual_payment'),
            // 'pay_4' => Db::name('wanlshop_order_goods')->alias('i')
            // ->join('wanlshop_order o','o.id=i.order_id','left')
            // ->where('o.createtime', 'between time', [$starttime, $endtime])
            // ->where('o.state','in','2,3,4,5,6')
            // ->where('i.gdtype','=','0')
            // ->sum('i.actual_payment'),
            'pay_3' => $list22['0']['sum'] ? $list22['0']['sum'] : 0,
            'pay_4' => $list23['0']['sum'] ? $list23['0']['sum'] : 0,

            'i_9' => $list9,
        ]);


        $this->assignconfig('starttime', $starttime);
        $this->assignconfig('endtime', $endtime);
        $this->assignconfig('column', array_keys($userlist));
        $this->assignconfig('userdata', array_values($userlist));
        $this->assignconfig('orderdata', array_values($orderlist));
        $this->assignconfig('order_sdata', array_values($order_slist));
        $this->assignconfig('orderdata2', array_values($orderlist2));
        $this->assignconfig('order_sdata2', array_values($order_slist2));
        $this->assignconfig('orderdata3', array_values($orderlist3));
        $this->assignconfig('order_sdata3', array_values($order_slist3));
        $this->assignconfig('orderdata4', array_values($orderlist4));
        $this->assignconfig('orderdata5', array_values($orderlist5));

        return $this->view->fetch();
    }

}
